<?php

/**
 * Created by PhpStorm.
 * User: feng
 * Date: 2016/12/18
 * Time: 下午5:13
 */
class Lyw_invite_code_manager_model extends CI_Model
{
    public function __construct()
    {
        $this->load->database();
    }

    public function getAllListInfo()
    {
        $sql = "select * from lyw_invite_code_manager order by id desc";
        $result = $this->db->query($sql)->result_array();
        return $result;
    }

    public function getAllListInfoIsVaild()
    {
        $sql = "select * from lyw_invite_code_manager where is_vaild = 1  order by id desc";
        $result = $this->db->query($sql)->result_array();
        return $result;
    }

    public function createCode()
    {

        for ($i = 0; $i < 10; $i++) {
            do {
                $code = $this->generate_str(4);
            } while ($this->hadCode($code));
            $creat_time = time();
            $sql = "insert into  lyw_invite_code_manager (code , creat_time) values ('{$code}' , {$creat_time});";
            $this->db->query($sql);
        }
        return true;
    }

    function generate_str($length = 4)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $password = '';
        for ($i = 0; $i < $length; $i++) {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
            $password .= $chars[mt_rand(0, strlen($chars) - 1)];
        }
        return $password;
    }

    function hadCode($code)
    {
        $sql = "select count(*) as count from lyw_invite_code_manager where code = '{$code}' and is_vaild = 1";
        $row = $this->db->query($sql)->row();
        if ($row->count > 0) {
            return true;
        } else {
            return false;
        }
    }

    function useCode($user_id, $code)
    {
        $sql = 'update lyw_invite_code_manager set user_id = ? , invited_time = ?,is_vaild = 0 where code = ? and is_vaild = 1';
        $this->db->query($sql, array($user_id, time(), $code));
        if ($this->db->affected_rows() == 1) {
            return true;
        } else {
            return false;
        }
    }
}